﻿using FastCloud.Base.Config;
using FastCloud.Base.Desgin;
using FastCloud.DMP.Entity;
using FastUtil.Data;
using System;
using System.Collections.Generic;
using System.Text;

namespace FastCloud.DMP.DB
{
    public class DB_Project : BaseDBML<Frame_Project>
    {
        public override void Insert(Frame_Project Entity)
        {
            if (string.IsNullOrEmpty(Entity.ProjectGuid))
            {
                Entity.ProjectGuid = GenerateUtil.GenerateUnitGuid();
            }
            Entity.ProjectCode = CloudUtil.CreateTableFieldCodeValue("Frame_Project", "ProjectGuid", "ProjectCode", "ParentProjectGuid", Entity.ParentProjectGuid,"10");
            Entity.AddDate = DateTime.Now;
            base.Insert(Entity);
        }

        public override void UpdateByID(Frame_Project Entity)
        {
            Frame_Project DBEntity = SelectOne(Entity.ProjectGuid);
            if (DBEntity.ParentProjectGuid != Entity.ParentProjectGuid)
            {
                Entity.ProjectGuid = CloudUtil.CreateTableFieldCodeValue("Frame_Project", "ProjectGuid", "ProjectCode", "ParentProjectGuid", Entity.ParentProjectGuid, "10");
                base.UpdateByID(Entity);
            }
            else
            {
                base.UpdateByID(Entity);
            }
        }


        /// <summary>
        /// 根据当前ProjectGuid获取此项目的所有层级父级项目（包括自身）
        /// </summary>
        /// <param name="ProjectGuid"></param>
        /// <returns></returns>
        public List<Frame_Project> SelectAllDeepByProjectGuid(string ProjectGuid)
        {
            List<Frame_Project> ResultEntityList = new List<Frame_Project>();
            List<Frame_Project> AllEntityList = SelectAllList();
            SearchParent(ProjectGuid, AllEntityList, ref ResultEntityList);
            return ResultEntityList;
        }

        private void SearchParent(string ProjectGuid, List<Frame_Project> AllEntityList,ref List<Frame_Project>  ResultEntityList)
        {
            Frame_Project Temp = AllEntityList.Find(a => a.ProjectGuid == ProjectGuid);
            ResultEntityList.Add(Temp);
            if (Temp.ParentProjectGuid!="Top")
            {
                //此前项目非顶级项目
                SearchParent(Temp.ParentProjectGuid, AllEntityList, ref ResultEntityList);
            }
        }

    }
}
